<?php
namespace app\controllers;

use laiq\base\Controller;


class ApiController extends Controller
{
    protected $params;
    protected $allowOrigin = [
        'http://localhost:9527'
    ];

    protected function initHeader() {
        foreach ($this->allowOrigin as $origin) {
            header('Access-Control-Allow-Origin:'.$origin);
        }
        header("Access-Control-Allow-Methods: *");
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, x-token");
    }

    protected function allowCredit() {
        header('Access-Control-Allow-Credentials:true');
    }

    protected function json($data) {
        header('Content-Type:application/json');
        echo json_encode($data);
        exit;
    }

    public function __construct($module, $controller, $action)
    {
        parent::__construct($module, $controller, $action);
        $this->initHeader();
        $this->allowCredit();
        $requestMethod = $_SERVER['REQUEST_METHOD'];
        $sLogContent = sprintf("Method:%s Url:%s\nParam:%s\n", $requestMethod, $_SERVER['REQUEST_URI'], file_get_contents('php://input'));
        file_put_contents('/data1/logs/api_request', $sLogContent);
        if ($requestMethod == 'OPTIONS') {
            exit;
        } elseif ($requestMethod == 'POST') {
            if (!empty($_SERVER['HTTP_CONTENT_TYPE']) && strpos($_SERVER['HTTP_CONTENT_TYPE'], ';') !== false) {
                $contentType = $_SERVER['HTTP_CONTENT_TYPE'];
                list($contentType, $charset) = explode(";", trim($contentType));
                if ($contentType == 'application/json') {
                    $body = file_get_contents('php://input');
                    $arJson = json_decode($body, true);
                    $_POST = array_merge($_POST, $arJson);
                }
            }
        }

    }

    public function __destruct()
    {
        file_put_contents('/data1/logs/api_request', file_get_contents('php://input'));
    }
}